package com.gateway.capture.module.netmodel.application.service.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.jnetpcap.packet.PcapPacket;
import org.jnetpcap.protocol.tcpip.Http;
import org.jnetpcap.protocol.tcpip.Http.Request;
import org.springframework.stereotype.Service;

import com.gateway.capture.module.netmodel.application.pojo.CustomHttp;
import com.gateway.capture.module.netmodel.application.service.HttpService;
import com.gateway.capture.utils.CopyUtils;

/**
 * @Description:抓包工具类
 * @author:hutao
 * @mail:hutao_2017@aliyun.com
 * @date:2021年9月2日
 */
@Service
public class HttpServiceImpl implements HttpService
{
    
    /**
     * @Description:提取http中的信息
     * @param
     * @author:hutao
     * @mail:hutao_2017@aliyun.com
     * @date:2021年9月13日
     */
    @Override
    public CustomHttp extractHttpInfo(PcapPacket packet)
    {
        if (!packet.hasHeader(Http.ID))
        {
            return null;
        }
        Http http = packet.getHeader(new Http());
        // 获取当前http请求中存在的请求头参数
        String[] fieldArray = http.fieldArray();
        Map<String, String> fieldMap = new HashMap<>();
        for (String temp : fieldArray)
        {
            fieldMap.put(temp.toUpperCase(), temp);
        }
        Map<String, String> httpParams = new ConcurrentHashMap<>();
        // 获取http定义的请求头参数
        Request[] valuesKeys = Request.values();
        for (Request value : valuesKeys)
        {
            // 使用hash进行匹配，将双重for变成一重for
            if (fieldMap.containsKey(value.name().toUpperCase().replace("_", "-")))
            {
                httpParams.put(value.toString(), http.fieldValue(value));
            }
        }
        CustomHttp customHttp = CopyUtils.copyMapToObject(httpParams, CustomHttp.class);
        // 获取http中请求的传输报文
        if (http.hasPayload())
        {
            try
            {
                byte[] payload = http.getPayload();
                String result = new String(payload, "UTF-8");
                customHttp.setData(result);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return customHttp;
    }
}
